<template>
	<view class="home-container" :style="containerStyle">
		<!-- 顶部导航栏 -->
		<nav-bar title="首页" :show-back="false" />

		<!-- 内容滚动区域 -->
		<scroll-view class="content-scroll" scroll-y>
			<!-- 项目统计卡片 -->
			<view class="stats-section">
				<view class="section-header">
					<text class="section-title">项目概览</text>
					<view class="add-btn" @tap="showCreateDialog = true">
						<text class="add-icon">+</text>
						<text class="add-text">新建项目</text>
					</view>
				</view>

				<view class="stats-cards">
					<view class="stat-card">
						<view class="stat-icon stat-icon-total">📊</view>
						<view class="stat-info">
							<text class="stat-value">{{ statistics.total }}</text>
							<text class="stat-label">总项目</text>
						</view>
					</view>

					<view class="stat-card">
						<view class="stat-icon stat-icon-progress">⏳</view>
						<view class="stat-info">
							<text class="stat-value">{{ statistics.inProgress }}</text>
							<text class="stat-label">进行中</text>
						</view>
					</view>

					<view class="stat-card">
						<view class="stat-icon stat-icon-completed">✅</view>
						<view class="stat-info">
							<text class="stat-value">{{ statistics.completed }}</text>
							<text class="stat-label">已完成</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 最新项目列表 -->
			<view class="projects-section">
				<view class="section-header">
					<text class="section-title">最新项目</text>
				</view>

				<view v-if="projects.length === 0" class="empty-state">
					<text class="empty-icon">📋</text>
					<text class="empty-text">暂无项目</text>
					<text class="empty-hint">点击右上角"新建项目"开始</text>
				</view>

				<view v-else class="project-list">
					<view v-for="project in projects" :key="project.id" class="project-card">
						<view class="project-header">
							<text class="project-name">{{ project.name }}</text>
							<view class="project-header-right">
								<view class="project-status" :class="'status-' + project.status">
									<text class="status-icon">{{ getStatusIcon(project.status) }}</text>
									<text class="status-text">{{ getStatusText(project.status) }}</text>
								</view>
								<view class="project-actions">
									<text class="action-icon" @tap.stop="handleEdit(project)">✏️</text>
									<text class="action-icon" @tap.stop="handleDelete(project)">🗑️</text>
								</view>
							</view>
						</view>

						<text v-if="project.description" class="project-desc">
							{{ project.description }}
						</text>

						<view class="project-progress">
							<view class="progress-bar">
								<view class="progress-fill" :style="{ width: project.progress + '%' }"></view>
							</view>
							<text class="progress-text">{{ project.progress }}%</text>
						</view>

						<view class="project-tasks">
							<view v-for="task in project.tasks" :key="task.id" class="task-item"
								:class="'task-' + task.status" @tap="handleTaskTap(project.id, task)">
								<text class="task-icon">{{ getTaskIcon(task.type) }}</text>
								<text class="task-name">{{ task.name }}</text>
								<text class="task-status">{{ getTaskStatusText(task.status) }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 新建项目弹窗 -->
		<uni-popup ref="createPopup" type="center" :mask-click="false">
			<view class="create-dialog">
				<view class="dialog-header">
					<text class="dialog-title">新建项目</text>
					<text class="dialog-close" @tap="closeCreateDialog">✕</text>
				</view>

				<view class="dialog-body">
					<view class="form-item">
						<text class="form-label">项目名称 <text class="required">*</text></text>
						<input class="form-input" v-model="formData.name" placeholder="请输入项目名称" maxlength="50" />
					</view>

					<view class="form-item">
						<text class="form-label">项目描述</text>
						<textarea class="form-textarea" v-model="formData.description" placeholder="请输入项目描述（可选）"
							maxlength="200">
					</textarea>
					</view>
				</view>

				<view class="dialog-footer">
					<view class="dialog-btn btn-cancel" @tap="closeCreateDialog">
						取消
					</view>
					<view class="dialog-btn btn-confirm" @tap="handleCreate">
						创建
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, watch } from 'vue';
	import { onShow } from '@dcloudio/uni-app';
	import NavBar from '@/components/nav-bar.vue';
	import { getThemeStyles } from '@/stores/theme';
	import type { Project, ProjectStatistics } from '@/types/project';
	import { ProjectStatus, TaskType, TaskStatus } from '@/types/project';
	import {
		getStatisticsAPI,
		getLatestAPI,
		createAPI,
		updateAPI,
		deleteAPI
	} from '@/services/project';
	import { showToast } from '@/utils/global';

	// 获取主题样式
	const themeStyles = computed(() => getThemeStyles());

	// 容器背景样式
	const containerStyle = computed(() => ({
		background: themeStyles.value.bgGradient
	}));

	// 项目统计数据
	const statistics = ref<ProjectStatistics>({
		total: 0,
		inProgress: 0,
		completed: 0,
		archived: 0
	});

	// 项目列表
	const projects = ref<Project[]>([]);

	// 创建项目弹窗显示状态
	const showCreateDialog = ref(false);

	// 弹窗引用
	const createPopup = ref();

	// 表单数据
	const formData = ref({
		name: '',
		description: ''
	});

	/**
	 * 加载数据
	 */
	const loadData = async () => {
		try {
			// 获取统计数据
			const statsRes = await getStatisticsAPI();
			statistics.value = statsRes.data || {
				total: 0,
				inProgress: 0,
				completed: 0,
				archived: 0
			};

			// 获取最新项目
			const projectsRes = await getLatestAPI({ page: 1, pageSize: 10 });
			// IPage对象的数据在records字段中
			projects.value = projectsRes.data.records || [];
		} catch (error : any) {
			console.error('加载数据失败:', error);
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			});
		}
	};

	/**
	 * 获取状态图标
	 */
	const getStatusIcon = (status : ProjectStatus) : string => {
		const iconMap = {
			[ProjectStatus.IN_PROGRESS]: '⏳',
			[ProjectStatus.COMPLETED]: '✅',
			[ProjectStatus.ARCHIVED]: '📦'
		};
		return iconMap[status] || '';
	};

	/**
	 * 获取状态文本
	 */
	const getStatusText = (status : ProjectStatus) : string => {
		const statusMap = {
			[ProjectStatus.IN_PROGRESS]: '进行中',
			[ProjectStatus.COMPLETED]: '已完成',
			[ProjectStatus.ARCHIVED]: '已归档'
		};
		return statusMap[status] || '';
	};

	/**
	 * 获取任务图标
	 */
	const getTaskIcon = (type : TaskType) : string => {
		return type === TaskType.PROFIT_PREDICTION ? '💰' : '📊';
	};

	/**
	 * 获取任务状态文本
	 */
	const getTaskStatusText = (status : TaskStatus) : string => {
		const statusMap = {
			[TaskStatus.NOT_STARTED]: '未开始',
			[TaskStatus.IN_PROGRESS]: '进行中',
			[TaskStatus.COMPLETED]: '已完成'
		};
		return statusMap[status] || '';
	};

	/**
	 * 格式化时间
	 */
	const formatTime = (time : string) : string => {
		const date = new Date(time);
		const now = new Date();
		const diff = now.getTime() - date.getTime();

		const minute = 60 * 1000;
		const hour = 60 * minute;
		const day = 24 * hour;

		if (diff < minute) {
			return '刚刚';
		} else if (diff < hour) {
			return `${Math.floor(diff / minute)}分钟前`;
		} else if (diff < day) {
			return `${Math.floor(diff / hour)}小时前`;
		} else if (diff < 7 * day) {
			return `${Math.floor(diff / day)}天前`;
		} else {
			return date.toLocaleDateString();
		}
	};

	/**
	 * 打开创建弹窗
	 */
	watch(showCreateDialog, (val) => {
		if (val && createPopup.value) {
			createPopup.value.open();
		}
	});

	/**
	 * 关闭创建弹窗
	 */
	const closeCreateDialog = () => {
		showCreateDialog.value = false;
		createPopup.value?.close();
		formData.value = {
			name: '',
			description: ''
		};
	};

	/**
	 * 创建项目
	 */
	const handleCreate = async () => {
		if (!formData.value.name.trim()) {
			uni.showToast({
				title: '请输入项目名称',
				icon: 'none'
			});
			return;
		}

		try {
			await createAPI({
				name: formData.value.name.trim(),
				description: formData.value.description.trim() || undefined
			});

			showToast('创建成功', 'success');

			closeCreateDialog();
			await loadData();
		} catch (error : any) {
			console.error('创建项目失败:', error);
			showToast(error.message || '创建失败', 'error');
		}
	};

	/**
	 * 点击任务卡片，根据任务类型跳转到对应页面
	 */
	const handleTaskTap = (projectId : string | number, task : any) => {
		// 根据任务类型跳转到对应页面
		if (task.type === TaskType.PROFIT_PREDICTION) {
			// 跳转到盈利预测页面
			uni.navigateTo({
				url: `/pages/index/profit-prediction/index?projectId=${projectId}&taskId=${task.id}`
			});
		} else if (task.type === TaskType.MARKET_RESEARCH) {
			// 跳转到客流预测页面
			uni.navigateTo({
				url: `/pages/index/market-research/index?projectId=${projectId}&taskId=${task.id}`
			});
		}
	};

	/**
	 * 编辑项目
	 */
	const handleEdit = (project : Project) => {
		uni.showModal({
			title: '编辑项目',
			editable: true,
			content: project.name,
			placeholderText: '请输入项目名称',
			success: async (res) => {
				if (res.confirm && res.content) {
					try {
						await updateAPI({
							id: project.id,
							name: res.content.trim()
						});
						showToast('修改成功', 'success');
						await loadData();
					} catch (error : any) {
						console.error('修改失败:', error);
						showToast(error.message || '修改失败', 'error');
					}
				}
			}
		});
	};

	/**
	 * 删除项目
	 */
	const handleDelete = (project : Project) => {
		uni.showModal({
			title: '确认删除',
			content: `确定要删除项目"${project.name}"吗？此操作不可恢复。`,
			success: async (res) => {
				if (res.confirm) {
					try {
						await deleteAPI(project.id);
						showToast('删除成功', 'success');
						await loadData();
					} catch (error : any) {
						console.error('删除失败:', error);
						showToast(error.message || '删除失败', 'error');
					}
				}
			}
		});
	};

	/**
	 * 页面显示时获取数据
	 * 每次进入页面（包括从其他页面返回）都会触发
	 */
	onShow(() => {
		loadData();
	});
</script>

<style scoped lang="scss">
	.home-container {
		min-height: 100vh;
		display: flex;
		flex-direction: column;

		.content-scroll {
			flex: 1;
			height: calc(100vh - var(--window-top));
			padding-bottom: 32rpx;

			.section-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 24rpx;

				.section-title {
					font-size: 34rpx;
					font-weight: 700;
					color: v-bind('themeStyles.textPrimary');
				}

				.add-btn {
					display: flex;
					align-items: center;
					gap: 8rpx;
					padding: 16rpx 24rpx;
					background: v-bind('themeStyles.primaryGradient');
					border-radius: 48rpx;
					box-shadow: v-bind('themeStyles.buttonBoxShadow');
					transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

					&:active {
						transform: scale(0.95);
						box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.2);
					}

					.add-icon {
						font-size: 32rpx;
						color: white;
						font-weight: 700;
					}

					.add-text {
						font-size: 28rpx;
						color: white;
						font-weight: 600;
					}
				}
			}

			.stats-section {
				padding: 32rpx;

				.stats-cards {
					display: flex;
					gap: 24rpx;

					.stat-card {
						flex: 1;
						background: v-bind('themeStyles.bgCard');
						border-radius: 24rpx;
						padding: 32rpx 24rpx;
						box-shadow: v-bind('themeStyles.cardBoxShadow');
						border: 1px solid v-bind('themeStyles.borderLight');
						display: flex;
						flex-direction: column;
						align-items: center;
						gap: 16rpx;
						transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

						&:active {
							transform: translateY(-4rpx);
							box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.12);
						}

						.stat-icon {
							width: 80rpx;
							height: 80rpx;
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
							font-size: 40rpx;

							&.stat-icon-total {
								background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
							}

							&.stat-icon-progress {
								background: linear-gradient(135deg, #f59e0b 0%, #ef4444 100%);
							}

							&.stat-icon-completed {
								background: linear-gradient(135deg, #10b981 0%, #059669 100%);
							}
						}

						.stat-info {
							display: flex;
							flex-direction: column;
							align-items: center;
							gap: 8rpx;

							.stat-value {
								font-size: 48rpx;
								font-weight: 700;
								color: v-bind('themeStyles.textPrimary');
							}

							.stat-label {
								font-size: 24rpx;
								color: v-bind('themeStyles.textSecondary');
							}
						}
					}
				}
			}

			.projects-section {
				padding: 0 32rpx 32rpx;

				.section-title {
					font-size: 34rpx;
					font-weight: 700;
					color: v-bind('themeStyles.textPrimary');
					margin-bottom: 24rpx;
				}

				.empty-state {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 80rpx 0;
					gap: 16rpx;

					.empty-icon {
						font-size: 96rpx;
						opacity: 0.3;
					}

					.empty-text {
						font-size: 32rpx;
						color: v-bind('themeStyles.textSecondary');
					}

					.empty-hint {
						font-size: 24rpx;
						color: v-bind('themeStyles.textTertiary');
					}
				}

				.project-list {
					display: flex;
					flex-direction: column;
					gap: 24rpx;

					.project-card {
						background: v-bind('themeStyles.bgCard');
						border-radius: 24rpx;
						padding: 32rpx;
						box-shadow: v-bind('themeStyles.cardBoxShadow');
						border: 1px solid v-bind('themeStyles.borderLight');
						transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

						&:active {
							transform: translateY(-4rpx);
							box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.12);
						}

						.project-header {
							display: flex;
							justify-content: space-between;
							align-items: flex-start;
							margin-bottom: 16rpx;
							gap: 16rpx;

							.project-name {
								flex: 1;
								font-size: 32rpx;
								font-weight: 600;
								color: v-bind('themeStyles.textPrimary');
								line-height: 1.4;
								word-break: break-word;
								min-width: 0;
							}

							.project-header-right {
								display: flex;
								align-items: center;
								gap: 12rpx;
								flex-shrink: 0;

								.project-status {
									display: flex;
									align-items: center;
									gap: 6rpx;
									padding: 8rpx 16rpx;
									border-radius: 24rpx;
									font-size: 22rpx;
									font-weight: 600;
									border: 2rpx solid transparent;
									transition: all 0.3s ease;
									white-space: nowrap;

									.status-icon {
										font-size: 24rpx;
										line-height: 1;
									}

									.status-text {
										line-height: 1;
									}

									// 进行中状态 (值为1) - 使用主题警告色（橙色）
									&.status-1 {
										background: v-bind('`${themeStyles.warningColor}0d`');
										color: v-bind('themeStyles.warningColor');
										border-color: v-bind('`${themeStyles.warningColor}33`');
									}

									// 已完成状态 (值为2) - 使用主题成功色（绿色）
									&.status-2 {
										background: v-bind('`${themeStyles.successColor}0d`');
										color: v-bind('themeStyles.successColor');
										border-color: v-bind('`${themeStyles.successColor}33`');
									}

									// 已归档状态 (值为3) - 使用主题次要文本色（灰色）
									&.status-3 {
										background: v-bind('`${themeStyles.textSecondary}0d`');
										color: v-bind('themeStyles.textSecondary');
										border-color: v-bind('`${themeStyles.textSecondary}33`');
									}
								}

								.project-actions {
									display: flex;
									gap: 16rpx;

									.action-icon {
										font-size: 32rpx;
										padding: 8rpx;
										transition: transform 0.2s ease;

										&:active {
											transform: scale(0.9);
										}
									}
								}
							}
						}

						.project-desc {
							font-size: 26rpx;
							color: v-bind('themeStyles.textSecondary');
							margin-bottom: 20rpx;
							line-height: 1.5;
						}

						.project-progress {
							display: flex;
							align-items: center;
							gap: 16rpx;
							margin-bottom: 20rpx;

							.progress-bar {
								flex: 1;
								height: 16rpx;
								background: v-bind('themeStyles.bgTertiary');
								border-radius: 8rpx;
								overflow: hidden;

								.progress-fill {
									height: 100%;
									background: v-bind('themeStyles.primaryGradient');
									border-radius: 8rpx;
									transition: width 0.3s ease;
								}
							}

							.progress-text {
								font-size: 24rpx;
								font-weight: 600;
								color: v-bind('themeStyles.textSecondary');
								min-width: 60rpx;
								text-align: right;
							}
						}

						.project-tasks {
							display: flex;
							gap: 12rpx;
							margin-bottom: 16rpx;

							.task-item {
								flex: 1;
								display: flex;
								flex-direction: column;
								align-items: center;
								gap: 8rpx;
								padding: 16rpx;
								background: v-bind('themeStyles.bgSecondary');
								border-radius: 16rpx;
								border: 2rpx solid transparent;
								cursor: pointer;
								transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

								&:active {
									transform: scale(0.95);
									box-shadow: v-bind('themeStyles.activeShadow');
								}

								// 未开始状态 - 使用主题信息色（蓝色）
								&.task-1 {
									background: v-bind('`${themeStyles.infoColor}0d`');
									border-color: v-bind('`${themeStyles.infoColor}33`');

									&:active {
										background: v-bind('`${themeStyles.infoColor}1a`');
									}

									.task-status {
										color: v-bind('themeStyles.infoColor');
									}
								}

								// 进行中状态 - 使用主题警告色（橙色）
								&.task-2 {
									background: v-bind('`${themeStyles.warningColor}0d`');
									border-color: v-bind('`${themeStyles.warningColor}33`');

									&:active {
										background: v-bind('`${themeStyles.warningColor}1a`');
									}

									.task-status {
										color: v-bind('themeStyles.warningColor');
									}
								}

								// 已完成状态 - 使用主题成功色（绿色）
								&.task-3 {
									background: v-bind('`${themeStyles.successColor}0d`');
									border-color: v-bind('`${themeStyles.successColor}33`');

									&:active {
										background: v-bind('`${themeStyles.successColor}1a`');
									}

									.task-status {
										color: v-bind('themeStyles.successColor');
									}
								}

								.task-icon {
									font-size: 32rpx;
								}

								.task-name {
									font-size: 24rpx;
									color: v-bind('themeStyles.textPrimary');
									font-weight: 500;
								}

								.task-status {
									font-size: 22rpx;
									color: v-bind('themeStyles.textTertiary');
								}
							}
						}

						.project-time {
							font-size: 22rpx;
							color: v-bind('themeStyles.textTertiary');
						}
					}
				}
			}
		}

		.create-dialog {
			width: 600rpx;
			background: v-bind('themeStyles.bgCard');
			border-radius: 24rpx;
			overflow: hidden;

			.dialog-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 32rpx;
				border-bottom: 1rpx solid v-bind('themeStyles.borderLight');

				.dialog-title {
					font-size: 34rpx;
					font-weight: 700;
					color: v-bind('themeStyles.textPrimary');
				}

				.dialog-close {
					font-size: 40rpx;
					color: v-bind('themeStyles.textSecondary');
					line-height: 1;
					padding: 8rpx;

					&:active {
						opacity: 0.6;
					}
				}
			}

			.dialog-body {
				padding: 32rpx;

				.form-item {
					margin-bottom: 32rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.form-label {
						display: block;
						font-size: 28rpx;
						font-weight: 500;
						color: v-bind('themeStyles.textPrimary');
						margin-bottom: 16rpx;

						.required {
							color: #ef4444;
						}
					}

					.form-input {
						width: 100%;
						height: 88rpx;
						padding: 0 24rpx;
						border: 2rpx solid v-bind('themeStyles.borderLight');
						border-radius: 16rpx;
						font-size: 28rpx;
						color: v-bind('themeStyles.textPrimary');
						background: v-bind('themeStyles.bgSecondary');
						transition: all 0.3s ease;

						&:focus {
							border-color: #667eea;
							background: v-bind('themeStyles.bgCard');
						}
					}

					.form-textarea {
						width: 100%;
						min-height: 160rpx;
						padding: 24rpx;
						border: 2rpx solid v-bind('themeStyles.borderLight');
						border-radius: 16rpx;
						font-size: 28rpx;
						color: v-bind('themeStyles.textPrimary');
						background: v-bind('themeStyles.bgSecondary');
						transition: all 0.3s ease;

						&:focus {
							border-color: #667eea;
							background: v-bind('themeStyles.bgCard');
						}
					}
				}
			}

			.dialog-footer {
				display: flex;
				gap: 24rpx;
				padding: 32rpx;
				border-top: 1rpx solid v-bind('themeStyles.borderLight');

				.dialog-btn {
					flex: 1;
					height: 88rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 16rpx;
					font-size: 30rpx;
					font-weight: 600;
					transition: all 0.3s ease;

					&:active {
						transform: scale(0.98);
					}

					&.btn-cancel {
						background: v-bind('themeStyles.bgSecondary');
						color: v-bind('themeStyles.textSecondary');
						border: 2rpx solid v-bind('themeStyles.borderLight');
					}

					&.btn-confirm {
						background: v-bind('themeStyles.primaryGradient');
						color: white;
						box-shadow: v-bind('themeStyles.buttonBoxShadow');
					}
				}
			}
		}
	}
</style>